package com.itggm.controller;


import com.itggm.Result.ResponseResult;
import com.itggm.dto.TemplatePageDTO;
import com.itggm.pojo.Template;
import com.itggm.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

 /**
  * @Author: ggm
  * @date:  2025/1/2
  */
@Slf4j
@RestController
@RequestMapping("template")
public class TemplateController {

    @Resource
    private TemplateService templateService;

    // 分页
    @PostMapping("page")
    public ResponseResult templatePage(@RequestBody TemplatePageDTO templatePageDTO){
        log.info("分页查询:{}",templatePageDTO);
       return templateService.templatePage(templatePageDTO);
    }


    // 文件上传
    @PostMapping("upload")
    public ResponseResult uploadTemplate(MultipartFile file){
        log.info("文件上传:{}",file);
        return  templateService.upload(file);
    }

    @PostMapping("add")
    public ResponseResult addTemplateInfo(@RequestBody Template template){
        log.info("添加模板信息:{}",template);
        templateService.save(template);
        return ResponseResult.success();
    }

    @DeleteMapping("delete/{uuid}")
    public ResponseResult deleteTemplate(@PathVariable String uuid){
        log.info("删除模板信息:{}",uuid);
        return  templateService.deleteTemplate(uuid);

    }

    // 文件上传
    @PostMapping("download")
    public void downloadTemplate(@RequestBody HashMap<String,String> params , HttpServletResponse response){
        log.info("下载模板信息:{}",params);
        String uuid = params.get("uuid");
        // TODO  服务器部署时改写路径
        File f = new File("D:/upload/springboot/" + uuid);

        try {
            FileInputStream fileInputStream = new FileInputStream(f);
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
